package com.roc.web.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.ModuleCategory;
import com.roc.pojo.Operators;
import com.roc.pojo.PowerModel;
import com.roc.pojo.PowerModule;
import com.roc.service.IModelService;
import com.roc.service.IPagenitionService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/model")
public class PowerModelAction extends PaginationBaseAction{
	private Logger logger=LogManager.getLogger(PowerModelAction.class);
	private PowerModelSearchCondition searchCondition;
	private PowerModel modelHead;
	private List<String> list=new ArrayList<String>();
	
	@Autowired
	IPageService pagenitionService;
	@Autowired
	IModelService modelService;
	
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/model/powerModelQuery.jsp"),
	@Result(name = "error", location = "/error.jsp")})
	public String init(){
		 Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		 if(!op.getRoleType().equals(Role.SYSTEM.getCode())&&!op.getRoleType().equals(Role.O_MANAGER.getCode())&&!op.getRoleType().equals(Role.AGENT.getCode())&&!op.getRoleType().equals(Role.OPERATORS_COMM.getCode())&&!op.getRoleType().equals(Role.OPERATORS_LEAD.getCode())){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
		return SUCCESS;
	}
	
	@Action(value = "queryModel", 
			results = { @Result(name = "success", location = "/pages/model/powerModelQuery.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String queryModel(){
	    Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
	    if(logingOperators.getRoleType().equals(Role.AGENT.getCode()) && !logingOperators.getAccountNo().equals("sdsyb")){
			 addActionError("无权访问");
			 return ERROR;
		 }
		
		if(searchCondition==null){
			searchCondition=(PowerModelSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new PowerModelSearchCondition();
			}
		}
		try {
			init(); 
			
			searchCondition.setOperatorsId(logingOperators.getId());
			
			int rows=pagenitionService.count(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAll(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);

			}
			dealWithTheListSpecially(searchRsList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		} catch (ServiceException e) {
			
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		
		return SUCCESS;
	}
	
	@Action(value = "addModel", 
			results = { @Result(name = "success", location = "/pages/model/addModel.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String addModel(){
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(logingOperators.getRoleType().equals(Role.AGENT.getCode()) && !logingOperators.getAccountNo().equals("sdsyb")){
			 addActionError("无权访问");
			 return ERROR;
		 }
		List<ModuleCategory> moduleList=new ArrayList<ModuleCategory>();
		try{
			modelHead=new PowerModel();
			modelHead.setModelCode(Constance.formateDate(new Date(), "yyyyMMddHHmmss"));
			moduleList=modelService.queryAllModuleCategoryList();
			getRequest().setAttribute("moduleList", moduleList);
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		
		return SUCCESS;
		
	}
	
	@Action(value = "saveModel", 
			results = { @Result(name = "success", location = "/pages/model/powerModelQuery.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String saveModel(){
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(logingOperators.getRoleType().equals(Role.AGENT.getCode()) && !logingOperators.getAccountNo().equals("sdsyb")){
			 addActionError("无权访问");
			 return ERROR;
		 }
		try{
			modelHead.setOperatorsId(logingOperators.getId());
			modelService.saveModelBatch(logingOperators, this.getList(), modelHead);
			
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		
		return queryModel();
	}
	
	@Action(value = "modifModel", 
			results = { @Result(name = "success", location = "/pages/model/modifModel.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String modifModel(){
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(logingOperators.getRoleType().equals(Role.AGENT.getCode()) && !logingOperators.getAccountNo().equals("sdsyb")){
			 addActionError("无权访问");
			 return ERROR;
		 }
		List<ModuleCategory> moduleList=new ArrayList<ModuleCategory>();
		try{
		    modelHead=modelService.queryModelById(this.getMulti_sel().get(0));
			List<PowerModule> moduleModelList=modelService.queryModule(modelHead.getOperatorsId(), modelHead.getModelCode());
			moduleList=modelService.queryAllModuleCategoryList();
			
			getRequest().setAttribute("moduleList", moduleList);
			getRequest().setAttribute("moduleModelList", moduleModelList);

			
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		
	
		return SUCCESS;
	}
	
	@Action(value = "saveModif", 
			results = { @Result(name = "success", location = "/pages/model/powerModelQuery.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String saveModif(){
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(logingOperators.getRoleType().equals(Role.AGENT.getCode()) && !logingOperators.getAccountNo().equals("sdsyb")){
			 addActionError("无权访问");
			 return ERROR;
		 }
		try{
			PowerModel model=modelService.queryModelById(modelHead.getId());
			model.setModelName(modelHead.getModelName());
			model.setRemark(modelHead.getRemark());
			List<PowerModule> moduleModelList=modelService.queryModule(model.getOperatorsId(), model.getModelCode());
			moduleModelList=dealSave(this.getList(),moduleModelList);
			modelService.updateSave(model,moduleModelList,logingOperators);

		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		
		return queryModel();
	}
	
	@Action(value = "delModel", 
			results = { @Result(name = "success", location = "/pages/model/powerModelQuery.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
    public String delModel(){
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(logingOperators.getRoleType().equals(Role.AGENT.getCode()) && !logingOperators.getAccountNo().equals("sdsyb")){
			 addActionError("无权访问");
			 return ERROR;
		 }
		try{
    		 modelHead=modelService.queryModelById(this.getMulti_sel().get(0));
    		 modelService.deleteModel(modelHead, logingOperators);
    	}catch(ServiceException e){
    		logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
    	}
    	return queryModel();
    }
	
	private List<PowerModule> dealSave(List<String> list,List<PowerModule> moduleModelList){
		List<PowerModule> tempList=new ArrayList<PowerModule>();
		PowerModule tempModule1=moduleModelList.get(0);
	
		for(String moduleCode:list){
			PowerModule tempModule2=new PowerModule();
			for(PowerModule tempModule:moduleModelList){
				if(moduleCode.equals(tempModule.getModuleCode())){
					tempModule2.setId(tempModule.getId());
					tempModule2.setDtCreate(tempModule.getDtCreate());
					tempModule2.setDtLostmod(tempModule.getDtLostmod());
				}
			}
			if(tempModule2.getId()==null||tempModule2.getId()==0){	
				tempModule2.setDtLostmod(new Date());	
			}
			tempModule2.setModuleCode(moduleCode);
			tempModule2.setModelCode(tempModule1.getModelCode());
		
			tempModule2.setOperatorsId(tempModule1.getOperatorsId());
			tempList.add(tempModule2);
		}
		
		return tempList;
	}
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		// TODO Auto-generated method stub
		this.searchCondition=(PowerModelSearchCondition) searchCondition;
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		// TODO Auto-generated method stub
		getSession().setAttribute(SEARCH_SESSION_BEAN_POWER_MODEL, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_BEAN_POWER_MODEL);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	public PowerModelSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(PowerModelSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public PowerModel getModelHead() {
		return modelHead;
	}

	public void setModelHead(PowerModel modelHead) {
		this.modelHead = modelHead;
	}

	public List<String> getList() {
		return list;
	}

	public void setList(List<String> list) {
		this.list = list;
	}
	
	

}
